<script setup>
import { onMounted, reactive, ref } from "vue"
import { list, deleteMany } from '@/api/bannerImage'
import { list as bannerList } from '@/api/banner'
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import { getImgUrl } from '@/api/request'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const totalRow = ref(0)
const pageSize = ref(10)
const tableRef = ref()

const formParams = [
  {
    param: 'banner_id',
    label: '所属banner',
    type: 'banner'
  },
]

const form = reactive({})
for (const i in formParams) {
  form[formParams[i].param] = null
}

async function loadData() {
  if (loading.value) return
  loading.value = true
  try {
    const res = await list({
      ...form,
      page: currentPage.value,
      page_size: pageSize.value
    })
    tableData.value = res.data
    totalRow.value = res.total
  } finally {
    loading.value = false
  }
  
}
const banners = ref([])
onMounted(async() => {
  banners.value = await bannerList({ page_size: -1 })
  loadData()
})

function gotoEdit(row) {
  router.push(`${route.path}/save?id=${row.id}`)
}
async function handleDelete(sel) {
  await deleteMany({ ids: sel.map(s => s.id) })
  ElMessage.success('删除成功')
  loadData()
}
function onPageChanged(p) {
  currentPage.value = p
  loadData()
}
function onPageSizeChanged(pz) {
  pageSize.value = pz
  loadData()
}
function onFormSubmit() {
  loadData()
}
function onFormReset() {
  for (const k in form) {
    form[k] = null
  }
  loadData()
}
function onInputClear() {
  loadData()
}
function onAddClick() {
  router.push(`${route.path}/save`)
}
// function getImgUrl(url) {
//   return import.meta.env.VITE_APP_IMG_BASE_URL + url
// }
const tableSelection = ref([])
function handleSelectionChange(sel) {
  console.log('handleSelectionChange', sel)
  tableSelection.value = sel
}
</script>

<template>
  <div>
    <el-form inline class="form-row" :model="form" @submit.native.prevent>
      <el-form-item v-for="item in formParams" :key="item.param" style="margin-right:10px">
        <span v-if="item.type && item.type != 'input'">
          <!-- 此处定义不同type的控件 -->
          <el-select v-if="item.type == 'banner'" v-model="form[item.param]"
          clearable @clear="onInputClear" :placeholder="item.label">
            <el-option v-for="item in banners" :key="item.id" :value="item.id" :label="item.name"  />
          </el-select>
        </span>
        <el-input v-else v-model="form[item.param]" 
          clearable @clear="onInputClear"
          :placeholder="item.label" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="onFormSubmit">查询</el-button>
        <el-button @click="onFormReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row style="margin: 8px 0">
      <el-popconfirm :title="`删除${tableSelection.length}条?`" 
        @confirm="handleDelete(tableSelection)"
      >
        <template #reference>
          <el-button :disabled="tableSelection.length<=0" type="danger">删除</el-button>
        </template>
      </el-popconfirm>
      <el-button @click="onAddClick">添加</el-button>
    </el-row>

    <el-table v-loading="loading" :data="tableData" 
      @selection-change="handleSelectionChange"
      ref="tableRef"
    >
      <el-table-column type="selection" />
      <el-table-column label="图片">
        <template #default="scope">
          <img class="img" :src="getImgUrl(scope.row.image)" />
        </template>
      </el-table-column>
      <el-table-column prop="banner.name" label="所属banner" />
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="url" label="url" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'danger':'success'">
            {{scope.row.status == 0 ? '禁用':'启用'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" />
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button size="small" @click="gotoEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="删除?" @confirm="handleDelete([scope.row])">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalRow"
      @current-change="onPageChanged"
      @size-change="onPageSizeChanged"
    />

  </div>
</template>

<style scoped>
  .form-row {
    display: flex;
    flex-wrap: wrap;
  }
  .img {
    width: 60px;
    height: 60px;
    background: #f2f2f2;
    object-fit: cover;
  }
</style>